#include "stackProtector.h"
#include <stdio.h>
#include <stdlib.h>

stack_t* stackProtector_init(void(*handler) (int))
{
  stack_t* stack = malloc(sizeof(stack_t));
  stack->ss_sp = valloc(SIGSTKSZ);
  if (stack->ss_sp == NULL)
    {
      fprintf(stderr, "Erreur: Malloc \n");
      exit(1);
    }   
  stack->ss_size = SIGSTKSZ;
  stack->ss_flags = 0;
  if (sigaltstack(stack, NULL) == -1)
    { 
      fprintf(stderr, "Erreur: sigalstack\n");
      exit(1);
    }

  //Mise en place du gestionnaire de signaux
  struct sigaction act;
  sigemptyset(&act.sa_mask);
  act.sa_handler = handler;
  act.sa_flags = SA_ONSTACK;
  sigaction(SIGSEGV,&act,NULL);

  return stack;
}

void stackProtector_free(stack_t* stack)
{
  free(stack->ss_sp);
  free(stack);
}
